package com.director.core.json.impl.gson;

import com.director.core.util.ReflectionUtils;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParseException;
import com.google.gson.JsonSerializationContext;
import com.google.gson.JsonSerializer;

import java.lang.reflect.Field;
import java.lang.reflect.Type;
import java.util.Arrays;
import java.util.List;

/**
 * @author Simone Ricciardi
 * @version 1.0, 04/07/2012
 */
public class ExcludeFieldsTypeAdapter<T> implements JsonSerializer<T> {

   private String[] fields = {};

   public ExcludeFieldsTypeAdapter(String[] fields) {
      this.fields = fields;
      Arrays.sort(this.fields);
   }

   @Override
   public JsonElement serialize(T src, Type typeOfSrc, JsonSerializationContext context) {
      try {
         JsonObject srcElement = new JsonObject();
         List<Field> fields = ReflectionUtils.hierarchicalGetDeclaredFields(src.getClass());
         for(Field field : fields) {
            String fieldName = field.getName();
            if(!this.isExcluded(fieldName)) {
               field.setAccessible(true);
               Object fieldValue = field.get(src);
               srcElement.add(fieldName, context.serialize(fieldValue));
            }
         }
         return srcElement;
      } catch(Exception e) {
         throw new JsonParseException(e);
      }
   }

   private boolean isExcluded(String fieldName) {
      return Arrays.binarySearch(this.fields, fieldName) >= 0;  
   }
}
